package pfq.demo.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * 各类引用的使用示例
 * Created by pangfuqiang on 2017/11/28.
 */

public class Main {

    public static void main(String[] args) {

        // 弱引用
        ReferenceQueue<Object> weakReferenceReferenceQueue = new ReferenceQueue<>();
        WeakReference<Data> weakReference = new WeakReference<>(new Data("WeakReference"), weakReferenceReferenceQueue);
        System.out.println("WeakReference: " + weakReference.get().content);
        WeakReference weakReference1;
        while ((weakReference1 = (WeakReference) weakReferenceReferenceQueue.poll()) != null) {
            System.out.println("WeakReference" + weakReference1);
        }


        // 虚引用
        ReferenceQueue<Data> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Data> phantomReference = new PhantomReference<>(new Data("PhantomReference"), referenceQueue);
        PhantomReference ref;
        while ((ref = (PhantomReference) referenceQueue.poll()) != null) {
            System.out.println("PhantomReference" + ref);
        }
        System.out.println("PhantomReference: " + phantomReference.get().content);

    }


    static class Data {
        public String content;

        public Data(String content) {
            this.content = content;
        }

    }

}
